<?php

namespace app\admin\controller;


use PhpMqtt\Client\MqttClient;
use PhpMqtt\Client\ConnectionSettings;

class Mqtt
{
    private $client;

    public function __construct($host, $port, $clientId)
    {
        $this->client = new MqttClient($host, $port, $clientId);
    }

    public function connect()
    {
        $settings = (new ConnectionSettings)
            ->setUsername('test') // 如果需要用户名
            ->setPassword('123456') // 如果需要密码
            ->setKeepAlive(60);

        $this->client->connect($settings);
    }

    public function publish($topic, $message)
    {
        $this->client->publish($topic, $message, 0);
    }

    public function subscribe($topic)
    {
        $this->client->subscribe($topic, 0);
        $this->client->loop(true); // 开始监听消息
    }

    public function disconnect()
    {
        $this->client->disconnect();
    }
}

$model = new Mqtt('113.44.136.17','1883',rand(5, 15));
